package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heima.admin.entity.AdUser;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.JwtUtils;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.dtos.AdUserLoginDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.management.Query;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author RMY
 * @since 2021-11-22
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    @Autowired
    private BCryptPasswordEncoder encoder;
    /**
     * 管理后台登陆
     * @param adUserLoginDto
     * @return
     */
    @Override
    public ResponseResult<Map<String, Object>> login(AdUserLoginDto adUserLoginDto) {
        //1.判断参数可直接省略，因为有@vaild
        //2.根据用户名查询数据库是否有adUser
        QueryWrapper<AdUser> qw = new QueryWrapper<>();
        qw.lambda().eq(AdUser::getName,adUserLoginDto.getName());
        //3.查询
        AdUser adUser = this.getOne(qw);
        //4.判断adUser
        if(adUser == null){
            //如果没查到,抛出异常
            throw new LeadException(AppHttpCodeEnum.AD_USER_NOT_EXIST);
        }
        //5.验证用户名和密码
        String password = adUser.getPassword();
        boolean b = encoder.matches(adUserLoginDto.getPassword(),password);
        //6.判断
        if (!b){
            //抛出异常
            throw new LeadException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //7.制作token
        String token = JwtUtils.generateTokenExpireInMinutes(adUser.getId(), 60);
        //8.封装返回结果
        Map<String,Object> map = new HashMap<>();
        map.put("user",adUser);
        map.put("token",token);
        return ResponseResult.ok(map);

    }
}
